package com.atguigu.newmvc.exceptionHandler;

import com.atguigu.newmvc.exception.BusException;
import com.atguigu.newmvc.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
public class GloableExceptionHandler {
    @ExceptionHandler(ArithmeticException.class)
    public R arithmeticExceptionHandler(ArithmeticException e){
        System.out.println("算数异常");
        return R.error(500,e.getCause()+e.getMessage());
    }
    @ExceptionHandler(FileNotFoundException.class)
    public R fileNotFoundException(FileNotFoundException e){
        System.out.println("文件未找到异常");
        return R.error(500,e.getCause()+e.getMessage());
    }
    @ExceptionHandler(NullPointerException.class)
    public R nullPointerException(NullPointerException e){
        System.out.println("空指针异常");
        return R.error(500,e.getCause()+e.getMessage());
    }
    @ExceptionHandler(BusException.class)
    public R busException(BusException e){
        System.out.println("业务异常");
        return R.error(500,e.getCause()+e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String,String> map = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach(fieldError -> {
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            map.put(field,defaultMessage);
        });
        return R.error(500,"校验异常",map);
    }

    @ExceptionHandler(Exception.class)
    public R exception(Exception e){
        System.out.println("其他异常");
        return R.error(500,e.getCause()+e.getMessage());
    }
}
